package com.zh.zookeeper;

import java.io.IOException;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.ZooDefs.Ids;

public class ZkTest2 implements Watcher {


	public static String url = "andSys.com:2181";
	
    public static String root  = "/zk";
    
    public static String child  = "/zk/child1";

	
	public static String authType = "digest";
	public static String authPasswd = "passwd";
	public static String authPasswd2 = "passwd2";
	
	public static void main(String[] args) {
		ZkTest2 zkTest2 = new ZkTest2();
		try {
			ZooKeeper zKeeper = new ZooKeeper(url, 3000, zkTest2);
			System.out.println("zk status:" + zKeeper.getState());
			//zKeeper.addAuthInfo(authType, authPasswd.getBytes());
			String createPath = null;
			
			//zKeeper.delete(child, -1);
			zKeeper.delete(root, -1);
			
			while(zKeeper.getState() != ZooKeeper.States.CONNECTED){
				Thread.sleep(3000);
			}
//			
//			while (!"CONNECTED".equals(zKeeper.getState().toString())) {
//				Thread.sleep(3000);
//			}
			if(null==zKeeper.exists(root, true)){
				createPath = zKeeper.create(root, "root".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
				System.out.println(createPath+"被创建");
			}
			if(null==zKeeper.exists(child, true)){
				String childPath = zKeeper.create(child, "child".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
				System.out.println(childPath+"被创建");
			}
			String rootdata = new String(zKeeper.getData(root, true, null));
			System.out.println(root+"节点数据是："+ rootdata);
			zKeeper.setData(root, "rootupdate1".getBytes(), -1);
			System.out.println(root+"节点数据是："+ rootdata);
	
			System.out.println(root+"子节点是："+ zKeeper.getChildren(root, true));
			System.out.println("-------------------------------");
			System.out.println(child+"节点数据是:"+ new String(zKeeper.getData(child, false, null)));
			zKeeper.setData(child, "child1update".getBytes(), -1);
			System.out.println(child+"节点数据是:"+ new String(zKeeper.getData(child, true, null)));
			
			
			
			zKeeper.close();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (KeeperException e) {
			e.printStackTrace();
		}

	}

	
	
	public void process(WatchedEvent event) {
		if(event.getType()==Watcher.Event.EventType.None){
			System.out.println("连接服务器成功！");
		}else if(event.getType()==Watcher.Event.EventType.NodeCreated){
			System.out.println("节点创建成功！");
			//重新读取配置
		}else if(event.getType()==Watcher.Event.EventType.NodeDataChanged){
			System.out.println("节点更新成功！");
		}else if(event.getType()==Watcher.Event.EventType.NodeDeleted){
			System.out.println("节点删除成功！");
		}else if(event.getType()==Watcher.Event.EventType.NodeChildrenChanged){
			System.out.println("子节点创建成功！");
			//重新读取配置
		}
		
		
		System.out.println("触发了事件："+event.getType());
	}

}
